package com.liu.netty.demo.client;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: https://www.joinsunsoft.com
 * @description:
 * @author: LiuYong
 * @email: david.liu@ginghan.com
 * @create: 2022/3/22 21:53
 */

@Slf4j
public class HeartBeatServerHandler extends ChannelHandlerAdapter{
    private int lossConnectCount = 0;

    @AllArgsConstructor
    @Data
    @ToString
    public static class CloseEvent{
        int count;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.error("========== userEventTriggered : {}", evt);

        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
                System.out.println("已经10秒未收到客户端的消息了！");
                lossConnectCount++;
                if (lossConnectCount>2){
                    ctx.fireUserEventTriggered(new CloseEvent(lossConnectCount));
                    System.out.println("关闭这个不活跃通道！");
                    ctx.channel().close();
                }
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
